import _ from 'lodash'
import CryptoJS from 'crypto-js'

export default {
  methods: {
    getToken () {
      return localStorage.getItem('token')
    },
    getUserID () {
      return localStorage.getItem('userID')
    },
    randomIv (len) {
      let $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789'
      let maxLen = $chars.length
      let res = ''
      for (let i = 0; i < len; i++) {
        res += $chars.charAt(Math.floor(Math.random() * maxLen))
      }
      return res
    },
    resolveReqConst (reqConst, obj) {
      let rC = this.cloneDeep(reqConst)
      if (rC.url.length === 0) return rC
      let s = rC.url
      for (let key in obj) {
        s = s.toString().replace(new RegExp('\\{\\{' + key + '\\}\\}', 'g'), obj[key])
      }
      rC.url = s
      return rC
    },
    resolveParamsReqConst (reqConst, pathObj, paramsObj) {
      let resolvingReqConst = this.resolveReqConst(reqConst, pathObj)
      let s = resolvingReqConst.url + '?'
      for (let p in paramsObj) {
        if (paramsObj[p]) {
          s = s + p + '=' + paramsObj[p] + '&'
        }
      }
      resolvingReqConst.url = s.substring(0, s.length - 1)
      return resolvingReqConst
    },
    // 深度拷贝
    cloneDeep (obj) {
      return _.cloneDeep(obj)
    },
    // 删除空值
    pickBy (obj) {
      return _.pickBy(obj, _.identity)
    },
    resetPageObj () {
      return {
        page: 1,
        pageSize: 10
      }
    },
    resolveMenuActive (path) {
      if (path.length === 0) return path
      if (path.indexOf('/show') !== -1) {
        return path.substring(0, path.indexOf('/show'))
      } else if (path.indexOf('/edit') !== -1) {
        return path.substring(0, path.indexOf('/edit'))
      } else if (path.indexOf('/new') !== -1) {
        return path.substring(0, path.indexOf('/new'))
      }
      return path
    },
    // 密码加密
    encrypt (value, iv) {
      return CryptoJS.AES.encrypt(value, CryptoJS.enc.Utf8.parse('etss313niubility'), {
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7,
        iv: CryptoJS.enc.Utf8.parse(iv)
      }).toString()
    },
    decryptEasy (value) {
      const key = CryptoJS.enc.Utf8.parse('etss313niubility') // 通过密钥获取128位的key
      const encryptedHexStr = CryptoJS.enc.Base64.parse(value) // 解码base64编码结果
      const encryptedBase64Str = CryptoJS.enc.Base64.stringify(encryptedHexStr)
      const decryptedData = CryptoJS.AES.decrypt(encryptedBase64Str, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return decryptedData.toString(CryptoJS.enc.Utf8)
    },
    getProperty (obj, str) {
      str = str.replace(/\[(\w+)\]/g, '.$1') // 处理数组下标
      let arr = str.split('.')
      for (let i in arr) {
        obj = (obj[arr[i]] || obj[arr[i]] === 0 || obj[arr[i]] === '0') ? obj[arr[i]] : '—'
      }
      return obj
    },
    logout () {
      localStorage.removeItem('token')
      localStorage.removeItem('username')
      this.$router.push({
        name: '/'
      })
    },
    getBase64 (url, callback) {
      // eslint-disable-next-line one-var
      let Img = new Image(),
        dataURL = ''
      Img.src = url + '?v=' + Math.random()
      Img.setAttribute('crossOrigin', 'Anonymous')
      Img.onload = function () {
        // eslint-disable-next-line one-var
        let canvas = document.createElement('canvas'),
          width = Img.width,
          height = Img.height
        canvas.width = width
        canvas.height = height
        canvas.getContext('2d').drawImage(Img, 0, 0, width, height)
        dataURL = canvas.toDataURL('image/jpeg')
        return callback ? callback(dataURL) : null
      }
    },
    checkIsJSON (str) {
      if (typeof str === 'string') {
        try {
          let obj = JSON.parse(str)
          return !!(typeof obj === 'object' && obj)
        } catch (e) {
          return false
        }
      }
      return false
    },
    err (msg) {
      this.$notify.error({
        message: msg,
        dangerouslyUseHTMLString: true,
        duration: 0,
        offset: 70
      })
    },
    warn (msg) {
      this.$notify({
        message: msg,
        dangerouslyUseHTMLString: true,
        type: 'warning',
        offset: 70
      })
    },
    info (msg) {
      this.$notify({
        message: msg,
        dangerouslyUseHTMLString: true,
        type: 'info',
        offset: 70
      })
    },
    success (msg) {
      this.$notify({
        message: msg,
        dangerouslyUseHTMLString: true,
        type: 'success',
        offset: 70
      })
    },
    toDecimal2 (x) {
      let f = parseFloat(x)
      if (isNaN(f)) {
        return false
      }
      f = Math.round(x * 100) / 100
      let s = f.toString()
      let rs = s.indexOf('.')
      if (rs < 0) {
        rs = s.length
        s += '.'
      }
      while (s.length <= rs + 2) {
        s += '0'
      }
      return s
    },
    isSaleDeadlineDate (startTime) {
      let sTime = new Date(startTime)
      sTime = sTime.setDate(sTime.getDate() - 1)
      let curTime = new Date()
      return curTime < sTime
    },
    isTokenExpired (_this, msg) {
      if (msg === '登录已失效，请重新登录') {
        _this.$router.push({path: '/login'})
      }
    },
    formatData (timer) {
      const year = timer.getFullYear()
      const month = timer.getMonth() + 1 // 由于月份从0开始，因此需加1
      const day = timer.getDate()
      const hour = timer.getHours()
      const minute = timer.getMinutes()
      const second = timer.getSeconds()
      return `${this.pad(year, 4)}-${this.pad(month)}-${this.pad(day)} ${this.pad(hour)}:${this.pad(minute)}:${this.pad(second)}`
    },
    pad (timeEl, total = 2, str = '0') {
      return timeEl.toString().padStart(total, str)
    }
  }
}
